// ==UserScript==
// @name         emby 弹幕脚本
// @namespace    http://tampermonkey.net/
// @version      1.01

// @author       caodan
// @match        */web/index.html
// @grant        none

// ==/UserScript==

let apiHost = "";



window.onload = async function(){
    apiHost = await getApiHost();
    // 判断是否为emby网页，如果是就载入弹幕插件
    let application_name = document.querySelector(`meta[name="application-name"]`).content;

    window.api_url = apiHost.endsWith("/") ? apiHost : apiHost + "/";
     // 设置延迟为5000毫秒（即5秒）
    setTimeout(loadDanmuku, 2000);

}



async function getApiHost(){
    let protocol = "https:"
    try {
          // 获取当前网址
        let currentUrl = window.location.href;
        // 创建一个URL对象
        let url = new URL(currentUrl);
        if(url.toString().startsWith("file")){
            let newHostname = getDefaultHostName();
            return `https://${newHostname}:8071`;
        }
        // 获取协议（http: 或 https:）
        protocol = url.protocol;
        // 获取主机名（包括子域名和顶级域名）
        let hostname = url.hostname;
        // 将前缀部分改成 "dm"
        let newHostname = `dm.${hostname.split(".").slice(1).join(".")}`;
            // 获取端口号（如果有的话）
        let port = url.port ? `:${url.port}` : "";
        // 生成新的域名字符串
        let newUrl = `${protocol}//${newHostname}${port}`;

        // 尝试使用 fetch 访问新生成的网址
        const response = await fetch(newUrl, { method: "HEAD" });
        if (response.ok) {
            return newUrl; // 如果访问成功，返回新生成的网址
        } else {
            throw new Error("Fetch failed"); // 如果响应状态不是 ok，抛出错误
        }
    } catch (error) {
        console.log("Error accessing new URL:", error);
        let newHostname = getDefaultHostName();
        let port = protocol=="https:" ? ":8071" : ":8072"
        return `${protocol}//${newHostname}${port}`;
    }

}

async function loadDanmuku(){
    // 载入jq库
    await loadJsScript("jquery-3.5.0.min.js");
    // 载入toastr库
    await loadJsScript("toastr.js");

    // 载入弹幕ede
    await loadJsScript("danmu-ede.js");

    // 载入弹幕库
    await loadJsScript("emby-danmu-app.js");


}


async function loadJsScript(js_name){
    const js_path = apiHost + "/static/js/" + js_name;
    return new Promise((resolve, reject) => {
        const script = document.createElement("script");
        //script.type = "text/javascript";
        script.src = js_path;
        script.onload = () => resolve(script);
        script.onerror = (error) => reject(error);
        document.head.appendChild(script);
        console.log("载入了js库" + js_name);
    });
}


// 混淆函数
function obfuscateString(str) {
    const offset = 3; // 偏移量
    let obfuscatedStr = "";
    for (let i = 0; i < str.length; i++) {
        obfuscatedStr += (str.charCodeAt(i) + offset).toString() + "-";
    }
    return obfuscatedStr;
}

// 解混淆函数
function deobfuscateString(obfuscatedStr) {
    const offset = 3; // 偏移量
    let deobfuscatedStr = "";
    const charCodes = obfuscatedStr.split("-").filter(Boolean); // 分割并过滤空字符串
    for (let i = 0; i < charCodes.length; i++) {
        deobfuscatedStr += String.fromCharCode(parseInt(charCodes[i]) - offset);
    }
    return deobfuscatedStr;
}

function getDefaultHostName(){
    return "dm." + "ainizai0905." + "top";
}





